package swt;

import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceAdapter;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

public class SWTDnDExample{

	public static void main(String[] args) {
		
		Display display = new Display();
		final Shell shell = new Shell(display);
		shell.setSize(520, 200);
		shell.setLayout(new RowLayout());
		shell.setText("DnD Example");

		Composite parent = new Composite(shell, SWT.NONE);
		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 4;
		parent.setLayout(gridLayout);
		
		String path = System.getProperty("user.dir") + "/images/";
		String[] imgNames = new String[] { "a_1.png", "b_1.png", "a_2.png", "b_2.png" };

		for (String imgName : imgNames){
			Label label = new Label(parent, SWT.NONE);
			Image img = new Image(display, path + imgName);
			label.setImage(img);
			label.setData("id", imgName);

			DragSource source = new DragSource(label, DND.DROP_NONE);
			source.setTransfer(new Transfer[] { TextTransfer.getInstance() });
			source.addDragListener(new DragSourceAdapter(){
				
				public void dragSetData(DragSourceEvent event) {
					DragSource ds = (DragSource) event.getSource();
					event.data = ds.getControl().getData("id");
				}
			});

			DropTarget target = new DropTarget(label, DND.DROP_NONE);
			target.setTransfer(new Transfer[] { TextTransfer.getInstance() });
			target.addDropListener(new DropTargetAdapter() {
				
				public void drop(DropTargetEvent event) {
					DropTarget dt = (DropTarget) event.getSource();
					String dragSourceId = (String) event.data;
					String dragTargetId = (String) dt.getControl().getData("id");
					
					if(dragSourceId.substring(0,1).equals(dragTargetId.substring(0,1))){
						MessageBox mb = new MessageBox(shell, SWT.ICON_WORKING);
						mb.setMessage("Match!");
						mb.open();
					}else{
						MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR);
						mb.setMessage("No Match!");
						mb.open();					
					}
				}
			});
		}

		shell.pack();
		shell.open();
		
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		display.dispose();
	}
}
	
